<template>
    <a-modal :keyboard="false" :maskClosable="false" title="用户编辑" :open="visible" :width="700" :confirmLoading="loading" centered @ok="handleSubmit" @cancel="handleCancel">
        <a-form layout="vertical">
            <a-row :gutter="16" type="flex" justify="start">
                <a-col :xs="12" :sm="12" :md="12">
                    <a-form-item label="姓名" v-bind="validateInfos.code">
                        <a-input v-model:value="modelRef.name" disabled>
                            <template #addonAfter>
                                <a-button type="text" size="small" @click="handleShowAccount">选择用户</a-button>
                            </template>
                        </a-input>
                    </a-form-item>
                </a-col>
                <a-col :xs="12" :sm="12" :md="12">
                    <a-form-item label="手机号" v-bind="validateInfos.workPhone">
                        <a-input v-model:value="modelRef.workPhone" disabled />
                    </a-form-item>
                </a-col>
                <a-col :xs="12" :sm="12" :md="12">
                    <a-form-item label="登录账号" v-bind="validateInfos.username">
                        <a-input v-model:value="modelRef.username" />
                    </a-form-item>
                </a-col>
                <a-col :xs="12" :sm="12" :md="12">
                    <a-form-item label="所属岗位" v-bind="validateInfos.jobName">
                        <a-input v-model:value="modelRef.jobName" disabled />
                    </a-form-item>
                </a-col>
                <a-col :xs="12" :sm="12" :md="12" v-if="showPw">
                    <a-form-item label="密码" v-bind="validateInfos.password">
                        <a-input v-model:value="modelRef.password" />
                    </a-form-item>
                </a-col>
                <a-col :xs="12" :sm="12" :md="12">
                    <a-form-item label="用户角色" v-bind="validateInfos.roleIds">
                        <a-select v-model:value="modelRef.roleIds" mode="multiple" style="width: 100%">
                            <a-select-option v-for="item in roleList" :key="item.id" :value="item.id" >
                                {{ item.name }}
                            </a-select-option>
                        </a-select>
                    </a-form-item>
                </a-col>
                <a-col :xs="12" :sm="12" :md="12">
                    <a-form-item label="有效期" v-bind="validateInfos.expireTime">
                        <a-date-picker show-time placeholder="不设置有效期为永久有效" v-model:value="modelRef.expireTime" valueFormat="YYYY-MM-DD HH:mm:ss"></a-date-picker>
                    </a-form-item>
                </a-col>
                <a-col :xs="12" :sm="12" :md="12">
                    <a-form-item label="负责项目" v-bind="validateInfos.projectCodes">
                        <a-tree-select
                            v-model:value="modelRef.projectCodes"
                            style="width: 100%"
                            tree-checkable
                            tree-default-expand-all
                            :height="233"
                            :field-names="{
                                children: 'children',
                                label: 'name',
                                value: 'code',
                            }"
                            :tree-data="treeData"
                            :max-tag-count="3"
                        ></a-tree-select>
                    </a-form-item>
                </a-col>
                <a-col :xs="12" :sm="12" :md="12">
                    <a-form-item label="负责条线" v-bind="validateInfos.txList">
                        <a-select v-model:value="modelRef.txList" mode="multiple" :options="txList" :field-names="{ value: 'name', label: 'name' }"></a-select>
                    </a-form-item>
                </a-col>
                <a-col :xs="12" :sm="12" :md="12">
                    <a-form-item label="用户状态" v-bind="validateInfos.status">
                        <a-radio-group v-model:value="modelRef.status">
                            <a-radio :value="1">启用</a-radio>
                            <a-radio :value="0">禁用</a-radio>
                        </a-radio-group>
                    </a-form-item>
                </a-col>
            </a-row>
        </a-form>

        <org-modal :model="{}" :visible="modalVisible" @cancel="modalVisible = false" @confirm="handleConfirm" />
    </a-modal>
</template>

<script lang="ts">
import type { PropType } from 'vue';
import { defineComponent, reactive, ref, watchEffect, watch, Ref, computed } from 'vue';
import { Form, message } from 'ant-design-vue';
import { createUser, updateUser, UpdateUserParams, getUser, getUserRole } from '@/api/user/account';
import { cloneDeep, isEmpty, isNull, isUndefined, isArray } from 'lodash-es';
import type { TreeProps } from 'ant-design-vue';
import { queryProjectTree } from '@/api/list/project-list';
import { getRolePage, getRoleAll } from '@/api/user/role';
import { txList as queryProline } from '@/api/common/proline';
import OrgModal from './org-modal.vue';
import dayjs from 'dayjs';

const fieldNames: TreeProps['fieldNames'] = {
    children: 'children',
    title: 'name',
    key: 'code',
};

export default defineComponent({
    props: {
        visible: {
            type: Boolean,
            required: true,
        },
        model: {
            type: Object as PropType<UpdateUserParams | null>,
            default: () => null,
        },
    },
    emits: ['cancel', 'success'],
    setup(props, { emit }) {
        const loading = ref(false);
        const treeData: Ref<TreeProps['treeData']> = ref([]);
        const roleList = ref<any[]>([]);
        const txList = ref<any[]>([]);
        const modelRef = reactive<any>({
            status: 1,
            projectCodes: [],
        });
        const rulesRef = reactive({
            code: [{ required: true, message: '请选择员工' }],
            roleIds: [{ required: true, message: '请选择角色' }],
            projectCodes: [{ required: true, message: '请设置负责项目' }],
            txList: [{ required: true, message: '请选择条线' }],
            password: [{ required: true, message: '请设置密码' }],
        });
        const { validateInfos, resetFields, validate } = Form.useForm(modelRef, rulesRef);

        // 记录初始值
        const initValues = reactive({});
        watch(
            () => props.visible,
            () => {
                Object.assign(initValues, cloneDeep(props.model));
            },
        );
        watchEffect(() => {
            if (props.visible) {
                queryProline().then(res => {
                    txList.value = res.data;
                });
                queryProjectTree().then(res => {
                    if (!isEmpty(res.data)) treeData.value.push(res.data as any);
                });
                getRoleAll({
                    current: 1,
                    size: 1000,
                }).then(res => {
                    if (!isEmpty(res.data)) roleList.value = res.data;
                });
                if (props.model) {
                    if (isUndefined(modelRef.id)) Object.assign(modelRef, props.model);

                    getUser(props.model.id).then(res => {
                        if (!isEmpty(res.data)) {
                            const { expireTime, projectCodeList, ...last } = res.data;

                            Object.assign(modelRef, last, {
                                projectCodes: projectCodeList,
                            });
                            if (!!expireTime) {
                                modelRef.expireTime = expireTime;
                            }
                        }
                    });
                }
            }
        });

        const showPw = computed(() => isUndefined(modelRef.id));

        const modalVisible = ref<boolean>(false);

        const handleShowAccount = () => {
            modalVisible.value = true;
        };

        const handleConfirm = (data: any) => {
            Object.assign(modelRef, data, {
                username: data.workPhone,
            });
            modalVisible.value = false;
            console.log(data);
            // getUserRole(data.code).then(res => {
            //     if (!isEmpty(res.data) && isArray(res.data)) modelRef.roleIds = res.data;
            // });
        };

        const handleCancel = () => {
            resetFields();
            Object.keys(modelRef).forEach(key => {
                delete modelRef[key];
            });
            modelRef.projectCodes = [];
            modelRef.status = 1;
            treeData.value = [];
            emit('cancel');
        };

        const handleSubmit = async () => {
            validate().then(() => {
                loading.value = true;
                const { expireTime, ...lastForm } = modelRef;
                const params: any = {
                    ...(lastForm as any),
                };
                if (!!expireTime) {
                    params.expireTime = dayjs(expireTime).format('YYYY-MM-DD HH:mm:ss');
                }
                if (isUndefined(modelRef.id) || isNull(modelRef.id)) params.password = 'yf12345.';
                (isUndefined(modelRef.id) || isNull(modelRef.id) ? createUser : updateUser)(params)
                    .then(res => {
                        if (res.data) {
                            message.success('操作成功');
                            emit('success');
                            handleCancel();
                        }
                    })
                    .finally(() => {
                        loading.value = false;
                    });
            });
        };
        return {
            loading,

            modelRef,
            validateInfos,
            resetFields,

            handleSubmit,
            handleCancel,

            initValues,
            fieldNames,
            treeData,
            roleList,
            txList,
            modalVisible,

            handleConfirm,
            handleShowAccount,

            isEmpty,

            showPw,
        };
    },
    components: {
        OrgModal,
    },
});
</script>
